<?php
namespace app\controller;

use app\BaseController;
use \think\facade\Request;
use \think\facade\Cache;
use \think\facade\Db;
use \think\facade\Log;
use EasyWeChat\Kernel\Support;

class Pay extends BaseController
{
    // 订单详情
    public function getOrderInfo()
    {
       $param = Request::param();
        $id = $param['id'];
        $order_info = Db::table('order_info')
                                ->where('id',$id)
                                ->find();
        $address_info = Db::table('user_address')
                                ->where('id',$order_info['address_id'])
                                ->find();
        $order_info['address_info'] = $address_info;

        return $this->returnJson(200,'操作成功',$order_info);
    }
    // 删除订单
    public function deleteOrder()
    {
       $param = Request::param();
        $id = $param['id'];
         $res =  Db::name('order_info')
                ->where('id',$id)
                ->useSoftDelete('delete_time',time())
                ->delete();
        if($res){
            return $this->returnJson(200,'操作成功',[]);
        }else{
            return $this->returnJson(400,'操作失败',[]);
        }
    }
	
	public function getOrderList()
	{
		$param = Request::param();
        $user_id = $this->getUserId();
		$page = $param['page'];
		$pageSize = $param['pageSize'];
		$status = $param['status']; // 1 待支付 2 已支付未配送 3已支付 配送中 4已完成

        
		$map = [];
		if(isset($param['status'])){
			if($param['status'] != -1){
				$myArray = array('status','=',$param['status']);
				array_push($map,$myArray);
			}
		}
		if(isset($param['type'])){
			if($param['type'] != -1){
				$myArray = array('type','=',$param['type']);
				array_push($map,$myArray);
			}
		}
		if(isset($param['ywy_order'])){ // 业务员查询订单 1 
			if($param['ywy_order'] == 1){
				$myArray = array('ywy_user_id','=',$user_id);
				array_push($map,$myArray);
			}else{
				$myArray = array('user_id','=',$user_id);
				array_push($map,$myArray);
			}
		}else{
			$myArray = array('user_id','=',$user_id);
			array_push($map,$myArray);
		}
	
		$list = Db::table('order_info')
					->where($map)
					->order('id','desc')
					->page($page,$pageSize)
                    ->whereNull('delete_time')
					->select()
					->all();
	
        foreach($list as $k=>$v){
            $list[$k]['spec'] = Db::table('goods')
                                ->where('id',$v['goods_id'])
                                ->value('spec');
        }
        
		$count = Db::table('order_info')
					->where($map)
                    ->whereNull('delete_time')
					->count();
		$res = [
			'result'=>$list,
			'count'=>$count
		];
		return $this->returnJson(200,'操作成功',$res);
	}
	// 商品兑换
    public function creatPointsOrder()
	{
		return $this->returnJson(400,'合作商才可以兑换商品',[]);
		$param = Request::param();
		$user_id = $this->getUserId();
        $goods_id = $param['goods_id'];
        $num = $param['num'];
        $type = $param['type']; // 1 商家配送 2 买家自提
        $address_id = $param['address_id']; // 地址id
		if(isset($param['pay_type']) && $param['pay_type']){
            $pay_type = $param['pay_type'];
        }else{
            $pay_type = 2;
        }
        

		// 启动事务
		Db::startTrans();
		try {
            $goods_info = Db::table('goods')
                    ->where('id',$goods_id)
                    ->find();
            
            // 获取用户积分
        $user_points = Db::table('point_water')
                    ->where('user_id',$user_id)
                    ->sum('points');
		$goods_info['need_price'] = abs($goods_info['need_price']);
        if($user_points < $goods_info['need_price']*$num){
            return $this->returnJson(400,'积分不足',[]);
        }

           $order = [
				'goods_id'=>$goods_id,
				'num'=>$num,
				'price'=>$goods_info['price'],
				'goods_name'=>$goods_info['goods_name'],
				'image'=>$goods_info['image'],
				'address_id'=>$address_id,
				'type'=>$type,
				'user_id'=>$user_id,
				'total_amount'=>$goods_info['price']*$num,
				'add_time'=>date("Y-m-d H:i:s"),
				'update_time'=>date("Y-m-d H:i:s"),
				'reward_points'=>$goods_info['reward_points']*$num,
                'pay_type'=>$pay_type,
                'use_point'=>$goods_info['need_price']*$num,
				'status'=>2,
				'pay_time'=>date("Y-m-d H:i:s"),
				'spec'=>$goods_info['spec'],
				'role'=>1,
			];
		  $order_id = Db::name('order_info')->insertGetId($order);
        
            // point_water
            Db::table('point_water')
                ->insert([
                    'goods_id'=>$goods_id,
                    'points'=>-($goods_info['need_price']*$num),
                    'user_id'=>$user_id,
                    'type'=>2,
                    'order_id'=>$order_id,
                    'add_time'=>date("Y-m-d H:i:s"),
                    'update_time'=>date("Y-m-d H:i:s"),
                    'num'=>$num,
                ]);

            // 更新用户积分
            Db::table('users')
                ->where('id',$user_id)
                ->update([
                    'point'=>$user_points-$goods_info['need_price']*$num,
                ]);

		return $this->returnJson(200,'操作成功',[]);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			return $this->returnJson(400,'',$e->getMessage());
			// 回滚事务
			Db::rollback();
		}
	}
    // 供应商商品兑换
    public function creatPointsOrderHzs()
	{
		$param = Request::param();
		$user_id = $this->getUserId();
        $goods_id = $param['goods_id'];
        $num = $param['num'];
        $type = $param['type']; // 1 商家配送 2 买家自提
        $address_id = $param['address_id']; // 地址id

		$pay_type = 2;
        

		// 启动事务
		Db::startTrans();
		try {
            $goods_info = Db::table('goods')
                    ->where('id',$goods_id)
                    ->find();
            
            // 获取用户积分
        $user_points = Db::table('point_water_hzs')
                    ->where('user_id',$user_id)
                    ->sum('points');
		$goods_info['hzs_need_points'] = abs($goods_info['hzs_need_points']);
        if($user_points < $goods_info['hzs_need_points']*$num){
            return $this->returnJson(400,'积分不足',[]);
        }

           $order = [
				'goods_id'=>$goods_id,
				'num'=>$num,
				'price'=>$goods_info['price'],
				'goods_name'=>$goods_info['goods_name'],
				'image'=>$goods_info['image'],
				'address_id'=>$address_id,
				'type'=>$type,
				'user_id'=>$user_id,
				'total_amount'=>$goods_info['price']*$num,
				'add_time'=>date("Y-m-d H:i:s"),
				'update_time'=>date("Y-m-d H:i:s"),
				'reward_points'=>0,
                'pay_type'=>$pay_type,
                'use_point'=>$goods_info['hzs_need_points']*$num,
				'status'=>2,
				'pay_time'=>date("Y-m-d H:i:s"),
				'spec'=>$goods_info['spec'],
				'role'=>2,
				'order_sn'=>createOrderSn(),
				'pay_order_sn'=>createOrderSn(),
			];
		  $order_id = Db::name('order_info')->insertGetId($order);
        
            // point_water
            Db::table('point_water_hzs')
                ->insert([
                    'goods_id'=>$goods_id,
                    'points'=>-($goods_info['hzs_need_points']*$num),
                    'user_id'=>$user_id,
                    'type'=>2,
                    'order_id'=>$order_id,
                    'add_time'=>date("Y-m-d H:i:s"),
                    'update_time'=>date("Y-m-d H:i:s"),
                    'num'=>$num,
                ]);

            // 更新用户积分
            Db::table('users')
                ->where('id',$user_id)
                ->update([
                    'point'=>$user_points-$goods_info['hzs_need_points']*$num,
                ]);

		return $this->returnJson(200,'操作成功',[]);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			return $this->returnJson(400,'',$e->getMessage());
			// 回滚事务
			Db::rollback();
		}
	}
	// 创建商品订单
	public function creatOrder()
	{
		$param = Request::param();
		$user_id = $this->getUserId();
        $goods_id = $param['goods_id'];
        $num = $param['num'];
        $type = $param['type']; // 1 商家配送 2 买家自提
        $address_id = $param['address_id']; // 地址id
		// $pay_type = $param['pay_type']; // 1 微信支付 2 积分兑换 3组合支付(积分+微信)
		if(isset($param['pay_type']) && $param['pay_type']){
            $pay_type = $param['pay_type'];
        }else{
            $pay_type = 1;
        }
        
         $goods_info = Db::table('goods')
                    ->where('id',$goods_id)
                    ->find();
        
		$need_points = 0;
		if($pay_type == 3){
			$need_points = Db::table('goods')
					->where('id',$goods_id)
					->value('need_points');
			$need_points = $need_points*$num;
			$need_points = abs($need_points);
			$user_points = Db::table('point_water')
                    ->where('user_id',$user_id)
                    ->sum('points');
			$goods_info['price'] = Db::table('goods')
					->where('id',$goods_id)
					->value('need_price');
			if($need_points > $user_points){
				return $this->returnJson(400,'','积分不足');
			}
		}
		// 启动事务
		Db::startTrans();
		try {
           
           $order = [
				'goods_id'=>$goods_id,
				'num'=>$num,
				'price'=>$goods_info['price'],
				'goods_name'=>$goods_info['goods_name'],
				'image'=>$goods_info['image'],
				'address_id'=>$address_id,
				'type'=>$type,
				'user_id'=>$user_id,
				'total_amount'=>$goods_info['price']*$num,
				'add_time'=>date("Y-m-d H:i:s"),
				'update_time'=>date("Y-m-d H:i:s"),
				'reward_points'=>$goods_info['reward_points']*$num,
                'pay_type'=>$pay_type,
				'spec'=>$goods_info['spec'],
				'use_point'=>$need_points,
				'is_pay_points'=>$pay_type == 3 ? 1 : 0,
				'order_sn'=>createOrderSn(),
				'pay_order_sn'=>createOrderSn(),
			];
		 $order_id = Db::name('order_info')->insertGetId($order);

		 $need_points = 0;
		if($pay_type == 3){
			Db::table('point_water')
				->insert([
					'goods_id'=>$goods_id,
					'points'=>-($need_points),
					'user_id'=>$user_id,
					'type'=>2,
					'order_id'=>$order_id,
					'add_time'=>date("Y-m-d H:i:s"),
					'update_time'=>date("Y-m-d H:i:s"),
					'num'=>$num,
				]);
		}


		return $this->returnJson(200,'操作成功',['id'=>$order_id]);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			return $this->returnJson(201,'',$e->getMessage());
			// 回滚事务
			Db::rollback();
		}
	}
	// 是否可以组合积分支付
	public function isPayPoints()
	{
		$param = Request::param();
		
		$order_id = $param['id'];
		$goods_id = Db::table('order_info')
					->where('id',$order_id)
					->value('goods_id');
		$num = Db::table('order_info')
					->where('id',$order_id)
					->value('num');
		$user_id = Db::table('order_info')
					->where('id',$order_id)
					->value('user_id');
		$is_pay_points = Db::table('order_info')
					->where('id',$order_id)
					->value('is_pay_points');
		// is_pay_points 不等于1 并且积分满足商品的need_points
		$need_points = Db::table('goods')
					->where('id',$goods_id)
					->value('need_points');
		$need_points = $need_points*$num;
		$need_points = abs($need_points);
		$user_points = Db::table('point_water')
                    ->where('user_id',$user_id)
                    ->sum('points');
		if($is_pay_points == 1){
			return $this->returnJson(200,'可以使用',['is_pay_points'=>2]);
		}
		if($need_points <= $user_points){
			return $this->returnJson(200,'可以使用',['is_pay_points'=>1]);
		}
		return $this->returnJson(200,'积分不足',['is_pay_points'=>0]);
	} 

	// 进行支付
	public function payNow()
	{
		$param = Request::param();
		$order_id = $param['id'];
		$pay_type = $param['pay_type'];  // 1 微信支付 2 积分兑换 3组合支付(积分+微信)
		$goods_id = Db::table('order_info')
					->where('id',$order_id)
					->value('goods_id');
		$num = Db::table('order_info')
					->where('id',$order_id)
					->value('num');
		$user_id = Db::table('order_info')
					->where('id',$order_id)
					->value('user_id');
	
		$need_points = 0;
		if($pay_type == 3){
			$need_points = Db::table('goods')
					->where('id',$goods_id)
					->value('need_points');
			$need_points = $need_points*$num;
			$need_points = abs($need_points);
			$user_points = Db::table('point_water')
                    ->where('user_id',$user_id)
                    ->sum('points');
			$goods_info['price'] = Db::table('goods')
					->where('id',$goods_id)
					->value('need_price');
			$total_amount = $goods_info['price']*$num;
			
			Db::table('order_info')
						->where('id',$order_id)
						->update([
							'total_amount'=>$total_amount,
						]);

			

			$is_pay_points = Db::table('order_info')
					->where('id',$order_id)
					->value('is_pay_points');

			 if($pay_type == 3 && $is_pay_points != 1){
			   if($need_points > $user_points){
				 return $this->returnJson(400,'积分不足',[]);
			   }
				Db::table('point_water')
					->insert([
						'goods_id'=>$goods_id,
						'points'=>-($need_points),
						'user_id'=>$user_id,
						'type'=>2,
						'order_id'=>$order_id,
						'add_time'=>date("Y-m-d H:i:s"),
						'update_time'=>date("Y-m-d H:i:s"),
						'num'=>$num,
					]);
					Db::table('order_info')
						->where('id',$order_id)
						->update([
							'is_pay_points'=>1,
							 'use_point'=>$need_points,
						]);
		   }

		}

        $order_sn = createOrderSn();
        Db::table('order_info')
                ->where('id',$order_id)
                ->update([
					'order_sn'=>$order_sn,
					'pay_type'=>$pay_type,
				]);

		$order_info = Db::table('order_info')
								->where('id',$order_id)
								->find();
								
		$user_id = $order_info['user_id'];
		
		$user_info = Db::table('users')
								->field('openid')
								->where('id',$user_id)
								->find();
		
		$app = $this->getEasyWeChatPayment();
		
		
		$domain = $this->domain;
		
	    $pay_data = [
				'body'=> '购买商品',
				'out_trade_no'=>$order_info['order_sn'],
				'total_fee'=> $order_info['total_amount']*100,
				'notify_url'=>$domain.'/pay/goodsNotic',
				'trade_type'=> 'JSAPI',
				'openid'=>$user_info['openid'],
	    ];
		    //  o1aiq7Qb0Xs_0kxsW7mjZgpGMPLg
		$result = $app->order->unify($pay_data);
		     
		 if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
					// 组装数据返回小程序
					$sign_param = [
						'appId' => $result['appid'],
						'nonceStr' => uniqid(),
						'package' => 'prepay_id=' . $result['prepay_id'],
						'signType' => 'MD5',
						'timeStamp' => time().''
					];
					$sign_param['paySign'] = Support\generate_sign($sign_param, $app->config->key, $sign_param['signType']);
					unset($sign_param['appId']);
				
				   return $this->returnJson(200,'',$sign_param);
		  }
	}
	// 购买商品支付回调
	public function goodsNotic()
	{
		$app = $this->getEasyWeChatPayment();
		$response = $app->handlePaidNotify(function ($message, $fail) {
			// Log::channel('pay')->info($message);
			$order_info = Db::table('order_info')
									->where('order_sn',$message['out_trade_no'])
									->find();
			if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
				Db::startTrans();
				try {
					if($order_info['status']==1){
    					Db::table('order_info')
    						->where('order_sn', $order_info['order_sn'])
    						->update([
    						        'status'=>2,
    						        'pay_time'=>date("Y-m-d H:i:s"),
    						   ]);
						if($order_info['reward_points'] && $order_info['reward_points']!=0){
							$dd1 = [
    						'points'=>$order_info['reward_points'],
    						'goods_id'=>$order_info['goods_id'],
    						'user_id'=>$order_info['user_id'],
    						'add_time'=>date("Y-m-d H:i:s"),
    						'update_time'=>date("Y-m-d H:i:s"),
    						'type'=>1,
							];
							$id = Db::name('point_water')->insertGetId($dd1);
						}
						// if($order_info['type']==3){
						// 	$order_info['use_point'] = abs($order_info['use_point']);
						// 	$dd2 = [
    					// 	'points'=>-$order_info['use_point'],
    					// 	'goods_id'=>$order_info['goods_id'],
    					// 	'user_id'=>$order_info['user_id'],
    					// 	'add_time'=>date("Y-m-d H:i:s"),
    					// 	'update_time'=>date("Y-m-d H:i:s"),
    					// 	'type'=>2,
						// 	];
						// 	$id = Db::name('point_water')->insertGetId($dd2);
						// }
    					
					}
					
					// 提交事务
					Db::commit();
				} catch (\Exception $e) {
					//回滚事务
					Db::rollback();
				}
			
			}
		});
	}
    
	

	
}